
%% copy riak-0.14.2 source to learn dynamo implementation and erlang
%% author: lichuang
-module(edynamo_ctl).

% remote control of the server
-export([start/0, process_command/1]).

-define(STATUS_SUCCESS, 0). 
-define(STATUS_ERROR,   1). 
-define(STATUS_USAGE,   2). 
-define(STATUS_BADRPC,  3). 

start() ->
  %size = app_helper:get_env(edynamo, ring_creation_size),
  %io:format("size: ~p~n", [size]),
  case init:get_plain_arguments() of
    [SNode | Args] ->
      Node = list_to_atom(SNode),
      io:format("Node ~p, args: ~p~n", [SNode, Args]),
      Status = case rpc:call(Node, ?MODULE, process_command, [Args]) of
		{badrpc, Reason} ->
		  io:format("RPC failed on the node ~p: ~p~n", [Node, Reason]),
		  ?STATUS_BADRPC;
		S ->
		  S
	       end,
      halt(Status);
    _ ->
      print_usage(),
      halt(?STATUS_USAGE)
  end.

process_command(["status"]) ->
  {InternalStatus, ProvidedStatus} = init:get_status(),
  io:format("Node ~p is ~p.Status: ~p~n",
    [node(), InternalStatus, ProvidedStatus]),
  case lists:keysearch(edynamo, 1, application:which_applications()) of
    false ->
      io:format("edynamo is not runnning"),
      ?STATUS_ERROR;
    {value, Version} ->
      io:format("edynamo version ~p is running~n", [Version]),
      ?STATUS_SUCCESS
  end;

process_command(["stop"]) ->
  init:stop(),
  ?STATUS_SUCCESS;

process_command(["restart"]) ->
  init:restart(),
  ?STATUS_SUCCESS;

process_command(_) ->
  print_usage(),
  ?STATUS_ERROR.

print_usage() ->
  io:format(
    "Usage: edynamoctl command~n"
    "~n"
    "Available commands:~n"
    "  stop~n"
    "  restart~n"
    "  status~n"
    "~n"
    "Example:~n"
    "  edynamoctl restart~n").
